package com.hd.trans.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.hd.trans.ui.base.AppContextProvider;

import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 剪贴板工具类
 */
public class ClipboardUtils {

    private static final ClipboardManager sClipboardManager = (ClipboardManager) AppContextProvider.getContext().getSystemService(Context.CLIPBOARD_SERVICE);

    public static ClipboardManager getClipboardManager(){
        return sClipboardManager;
    }

    public static void writeClipText(@Nullable CharSequence text,@Nullable Runnable successCallback){
        boolean isWrite = writeClipText(text);
        if (isWrite && successCallback != null){
            successCallback.run();
        }
    }

    /**
     * 写入文本到系统剪贴板
     * @param text 文本
     */
    public static boolean writeClipText(@Nullable CharSequence text){
        if (text == null)
            return false;
        String str = text.toString().trim();
        boolean success = false;
        if (TextUtils.isEmpty(str)){
            return false;
        }
        ClipboardManager cm = getClipboardManager();
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", str);
        // 将ClipData内容放到系统剪贴板里。
        try {
            cm.setPrimaryClip(mClipData);
            success = true;
        }
        catch (Exception ignored){ }

        return success;
    }

    public static boolean hasPrimaryClip(){
        return getClipboardManager().hasPrimaryClip();
    }

    /**
     * 读取系统剪贴板的文本
     * @return 剪贴板的文本
     */
    @Nullable
    public static String readClipText() {
        Context context = AppContextProvider.getContext();
        ClipboardManager clipboard = getClipboardManager();
        ClipData clip = clipboard.getPrimaryClip();
        String text = null;
        if (clip != null && clip.getItemCount() > 0) {
            try {
                text = clip.getItemAt(0).coerceToText(context).toString();
            }
            catch (Exception ignored){ }
        }

        if (text != null){
            text = text.trim();
        }

        if (TextUtils.isEmpty(text)){
            text = ClipDataCache.getClipDataAt(0);
        }
        else {
            ClipDataCache.saveClipData(text);
        }

        return TextUtils.isEmpty(text) ? null : text;
    }

    @NonNull
    public static String[] readClipAllText(){
        Context context = AppContextProvider.getContext();
        ClipboardManager clipboard = getClipboardManager();
        ClipData clip = clipboard.getPrimaryClip();
        List<String> textList = new ArrayList<>();
        String[] textArray = new String[0];

        if (clip != null && clip.getItemCount() > 0) {
            int itemCount = clip.getItemCount();
            try {
                for (int i = 0; i < itemCount; i++) {
                    ClipData.Item clipData = clip.getItemAt(i);
                    String text = clipData.coerceToText(context).toString();
                    if (!TextUtils.isEmpty(text)) {
                        textList.add(text);
                    }
                }
                textArray = textList.toArray(new String[0]);
            } catch (Exception ignored) { }
        }

        if (textArray.length == 0){
            textArray = ClipDataCache.getClipData();
        }
        else {
            ClipDataCache.saveClipData(textArray);
        }

        return textArray;
    }

    private static class ClipDataCache {
        static SharedPreferences sp = AppContextProvider.getContext().getSharedPreferences("clip_data", Context.MODE_PRIVATE);

        public static void saveClipData(String ...text){
            JSONArray jsonArray = new JSONArray(Arrays.asList(text));
            sp.edit().putString("clipData",jsonArray.toString()).apply();
        }

        public static String[] getClipData(){
            String jsonStr = sp.getString("clipData", "[]");
            String[] array = new String[0];
            try {
                JSONArray jsonArray = new JSONArray(jsonStr);
                array = new String[jsonArray.length()];
                for (int i = 0; i < jsonArray.length(); i++) {
                    array[i] = jsonArray.getString(i);
                }
            } catch (Exception ignored) { }
            return array;
        }

        public static String getClipDataAt(int index){
            String[] array = getClipData();
            if (index >= 0 && index < array.length){
                return array[index];
            }
            return null;
        }
    }

    public interface ReadTextCallback {
        void onCallback(String text);
    }

    public interface ReadTextListCallback {
        void onCallback(String[] texts);
    }

}
